<template>
    <div class="ele-body">
        <div class="container-div">
            <!-- 搜索表单 -->
            <!-- <vxe-toolbar>
                <template v-slot:buttons>
                    <vxe-input v-model="value100" placeholder="款号/商品名"></vxe-input>
                    <el-button type="primary" @click="getTable1()" icon="el-icon-search" class="ele-btn-icon"
                        :disabled="disabled" :loading="loadingGetTable">查看</el-button>
                    <el-button type="primary" @click="downloadExcel()" icon="el-icon-download" class="ele-btn-icon"
                        :disabled="disabled" :loading="loadingDownloadExcel">下载</el-button>
                    <el-button @click="createTable()" icon="el-icon-plus" class="ele-btn-icon" :disabled="disabled"
                        :loading="loadingCreateTable">生成报表</el-button>
                    <el-button @click="createExcel()" icon="el-icon-plus" class="ele-btn-icon" :disabled="disabled"
                        :loading="loadingCreateExcel">生成EXCEL</el-button>
                    <el-button type="text" class="ele-btn-icon" size="medium">生成报表时间：{{tableTime}}</el-button>
                </template>
            </vxe-toolbar> -->
            <el-form label-width="60px" class="ele-form-search" @keyup.enter.native="$refs.table.reload()"
                @submit.native.prevent>
                <el-row :gutter="15">
                    <el-col :md="3" :sm="12">
                        <el-form-item label="款号:"><el-input placeholder="款号或商品名" v-model="querys.cxspbh"
                                clearable></el-input></el-form-item>
                    </el-col>
                    <el-col :md="3" :sm="12">
                        <el-form-item label="供应商:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.gysid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_gys" :key="item.id" :label="item.name"
                                    :value="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :md="3" :sm="12">
                        <el-form-item label="仓店:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.cdid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_cd" :key="item.id" :label="item.name"
                                    :value="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :md="3" :sm="12">
                        <el-form-item label="区域:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.ppid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_pp" :key="item.id" :label="item.attribname"
                                    :value="item.attribname"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :md="3" :sm="12">
                        <el-form-item label="年份:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.nfid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_nf" :key="item.id" :label="item.attribname"
                                    :value="item.attribname"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :md="3" :sm="12">
                        <el-form-item label="季节:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.jjid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_jj" :key="item.id" :label="item.attribname"
                                    :value="item.attribname"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
					<el-col :md="3" :sm="12" v-if="$setting.showZdy">
							<el-form-item label="售罄率≥:" style="white-space: nowrap;">
							<el-input placeholder="请输入"  v-model="querys.sql"></el-input>
							</el-form-item>
					</el-col>
					<el-col :md="3" :sm="12" v-if="$setting.showZdy">
							<label><span>采购次数&ge;:</span>
							<el-input placeholder="请输入"  v-model="querys.cgcs" style="width:80px;"></el-input>
							</label>
					</el-col>
                </el-row>
                <el-row :gutter="12">
                    <el-col :md="3" :sm="12">
                        <el-form-item label="大类:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.dlid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_dl" :key="item.id" :label="item.attribname"
                                    :value="item.attribname"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :md="3" :sm="12">
                        <el-form-item label="中类:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.zlid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_zl" :key="item.id" :label="item.attribname"
                                    :value="item.attribname"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
					<!-- 时间段查询 -->
					<el-col :md="3" :sm="12" class="oneRowCol selectTime">
						<el-tooltip content=" 时间段" placement="top-start">
							<el-date-picker
							v-model="selectTime"
							type="daterange"
							value-format="yyyyMMdd"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							>
							</el-date-picker>
						</el-tooltip>
					</el-col>
                    <el-col :md="3" :sm="12" style="margin-left: 30px;">
                        <el-form-item label="小类:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.xlid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_xl" :key="item.id" :label="item.attribname"
                                    :value="item.attribname"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :md="3" :sm="12">
                        <el-form-item label="性别:">
                            <el-select style="width:100%" placeholder="请输入" v-model="querys.xbid" multiple clearable
                                filterable collapse-tags>
                                <el-option v-for="item in options_xb" :key="item.id" :label="item.attribname"
                                    :value="item.attribname"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
					<el-col :md="3" :sm="12">
						<el-form-item label="波段:">
							<el-select style="width:100%" placeholder="请输入" v-model="querys.bdid" multiple clearable
								filterable collapse-tags>
								<el-option v-for="item in options_bd" :key="item.id" :label="item.attribname"
									:value="item.attribname"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :md="3" :sm="12" v-if="$setting.showZdy">
							<label><span>到货天数&le;:</span>
							<el-input placeholder="请输入"  v-model="querys.dhts"  style="width:80px;"></el-input>
							</label>
					</el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :md="24" :sm="24">
                        <div class="ele-form-actions">
                            <el-button type="primary" @click="getTable1(1)" icon="el-icon-search" class="ele-btn-icon"
                                :disabled="disabled" :loading="loadingGetTable">查询</el-button>
                            <el-tooltip class="item" effect="dark" content="下载查询的数据到EXCEL" placement="top-start">
                                <el-button type="warning" @click="getExcel()" icon="el-icon-download" class="ele-btn-icon"
                                    :disabled="disabled" :loading="loadingGetExcel">下载</el-button>
                            </el-tooltip>
                            <el-button type="info" @click="selectReset()" icon="el-icon-delete" class="ele-btn-icon"
                                :disabled="disabled" >重置</el-button>
                            <el-button @click="createTable()" class="ele-btn-icon" :disabled="disabled"
                                v-permission="'qx_bbglqx'" :loading="loadingCreateTable">1生成报表</el-button>
                            <el-button @click="createExcel()" class="ele-btn-icon" :disabled="disabled"
                                v-permission="'qx_bbglqx'" :loading="loadingCreateExcel">2生成EXCEL</el-button>
                            <el-button @click="downloadExcel()" class="ele-btn-icon" :disabled="disabled"
                                v-permission="'qx_bbglqx'" :loading="loadingDownloadExcel">3下载所有</el-button>
                            <!-- <el-link v-if="searchExpand" @click="searchExpand = false" type="primary" :underline="false">
								收起
								<i class="el-icon-arrow-up"></i>
							</el-link>
							<el-link v-else @click="searchExpand = true" type="primary" :underline="false">
								更多
								<i class="el-icon-arrow-down"></i>
							</el-link> -->
                            <!-- <el-button type="text" class="ele-btn-icon" size="medium">报表时间:{{tableTime}}</el-button> -->
                            <el-link type="danger" :underline="false">报表时间：{{tableTime}}</el-link>
							<el-link :underline="false">报表时间段：{{this.data1}}-{{this.data2}}</el-link>
                        </div>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 数据表格1 -->
            <vxe-table ref="tabledyn" border stripe :highlight-current-row="true" size="mini" height="630px" resizable
                highlight-hover-row highlight-hover-column show-header-overflow show-overflow row-id="id"
				class="mytable-scrollbar"
                :loading="loading1" :data="tableData1">
                <!-- <vxe-table-column type="checkbox" width="48" fixed="left"></vxe-table-column> -->
                <!-- <vxe-table-column type="seq" title="序号" width="48" fixed="left"></vxe-table-column> -->
                <template v-for="(item, index) in tableColumn1">
                    <vxe-table-column :field="item.fieldcode" :title="item.fieldname" :min-width="item.showwidth"
                        :key="index"></vxe-table-column>
                </template>
            </vxe-table>

            <!-- 表格分页 -->
            <vxe-pager :loading="loading1" :current-page="tablePage1.currentPage" :page-size="tablePage1.pageSize"
                :total="tablePage1.totalResult"
                :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                @page-change="handlePageChange1">
            </vxe-pager>
        </div>
    </div>
</template>

<script>
    // import XEUtils from'xe-utils'

    export default {
        name: 'BiJxcbb', //进销存报表
        data() {
            return {
                loading1: false,
                tableData1: [],
                tablePage1: {
                    currentPage: 1,
                    pageSize: 20,
                    totalResult: 0
                },
                tableColumn1: [],
                tableTime: '--',
                loadingCreateTable: false,
                loadingGetTable: false,
                loadingCreateExcel: false,
                loadingDownloadExcel: false,
                loadingGetExcel: false,
                disabled: false,

                searchExpand: false, // 搜索表单是否展开

                //基础查询条件（品牌pp、年份nf、季节jj、小类xl、性别xb）
                options_pp: [],
                options_nf: [],
                options_jj: [],
                options_xb: [],
                options_dl: [],
                options_zl: [],
                options_xl: [],
				options_bd: [],
                options_gys: [], //供应商
                options_cd: [], //仓店
                //查询条件
                querys: {
                    ppid: [],
                    nfid: [],
                    jjid: [],
                    xbid: [],
                    dlid: [],
                    zlid: [],
                    xlid: [],
                    gysid: [],
                    cdid: [],
					bdid: [],
                    cxspbh: null, //手动输入的款号
					sql: null, //售罄率
					cgcs: null,//采购次数
					dhts: null //到货天数
                },
				selectTime:[],
				data1 : null,
				data2 : null,
				pdSfZj : true
            }
        },
        created() {
            //品牌
          /*  this.$http.post('/scm/base/productAttr?attr=01').then(res => {
                this.options_pp = res.data.data;
            });
            //年份
            this.$http.post('/scm/base/productAttr?attr=02').then(res => {
                this.options_nf = res.data.data;
            });
            //季节
            this.$http.post('/scm/base/productAttr?attr=03').then(res => {
                this.options_jj = res.data.data;
            });
            //性别
            this.$http.post('/scm/base/productAttr?attr=05').then(res => {
                this.options_xb = res.data.data;
            });
            //大类
            this.$http.post('/scm/base/productAttr?attr=07').then(res => {
                this.options_dl = res.data.data;
            });
            //中类
            this.$http.post('/scm/base/productAttr?attr=08').then(res => {
                this.options_zl = res.data.data;
            });
            //小类
            this.$http.post('/scm/base/productAttr?attr=09').then(res => {
                this.options_xl = res.data.data;
            });
			//波段
			this.$http.post('/scm/base/productAttr?attr=04').then(res => {
				this.options_bd = res.data.data;
			}); */
			
			// 动态属性
			this.selectAttribList();
            //供应商
            this.$http.post('/scm/base/supplier').then(res => {
                this.options_gys = res.data.data;
            });
            //仓店
            this.$http.post('/scm/base/store').then(res => {
                this.options_cd = res.data.data;
            });

            // this.findList1();
            this.getTableTime();
            this.getTable1();


        },
        methods: {
			//下拉筛选条件
			selectAttribList() {
				this.$http.post('/scm/buhuo/zbbh/selectAllAttrib').then(res => {
					this.attribList = res.data
						this.attribList.forEach(res => {
						if (res.dtzd == 'dtzd_pp') {
							this.$http.post('/scm/buhuo/zbbh/selctAttribById', {
								attr: res.id
							}).then(n => {
								this.options_pp = n.data  //品牌
							})
							}
						if (res.dtzd == 'dtzd_nf') {
							this.$http.post('/scm/buhuo/zbbh/selctAttribById', {
								attr: res.id
							}).then(n => {
								this.options_nf = n.data  //年份
							})
						}	
						if (res.dtzd == 'dtzd_jj') {
							this.$http.post('/scm/buhuo/zbbh/selctAttribById', {
								attr: res.id
							}).then(n => {
								this.options_jj = n.data  //季节
							})
						}
						if (res.dtzd == 'dtzd_xb') {
							this.$http.post('/scm/buhuo/zbbh/selctAttribById', {
								attr: res.id
							}).then(n => {
								this.options_xb = n.data   //性别
							})
						}
						if (res.dtzd == 'dtzd_dl') {
							this.$http.post('/scm/buhuo/zbbh/selctAttribById', {
								attr: res.id
							}).then(n => {
								this.options_dl = n.data   //大类
							})
						}
						if (res.dtzd == 'dtzd_zl') {
							this.$http.post('/scm/buhuo/zbbh/selctAttribById', {
								attr: res.id
							}).then(n => {
								this.options_zl = n.data     //中类
							})
						}
						if (res.dtzd == 'dtzd_xl') {
							this.$http.post('/scm/buhuo/zbbh/selctAttribById', {
								attr: res.id
							}).then(n => {
								this.options_xl = n.data       //小类
							})
						}
						if (res.dtzd == 'dtzd_bd') {
							this.$http.post('/scm/buhuo/zbbh/selctAttribById', {
								attr: res.id
							}).then(n => {
								this.options_bd = n.data       //波段
							})
						}
					})
				})
			},
            //获取生成报表数据的时间
			getTableTime() {
				this.$http.post('/scm/bi/getTableTime/jxcbb', {})
					.then(res => {
						this.tableTime = res.data.tableTime || '';
						if (res.data.code == 0) {
							this.tableTime = res.data.tableTime || '';
						} else {
							this.$message.error(res.data.msg);
						}
					})
					.catch(e => {
						this.$message.error(e.message);
					});
			},
            //清空筛选
            selectReset() {
                this.querys.cdid = []; //仓店ID
                this.querys.gysid = []; //供应商ID
                this.querys.cxspbh = null; //手输商品款号
                this.querys.ppid = []; //品牌
                this.querys.nfid = []; //年份
                this.querys.jjid = []; //季节
                this.querys.dlid = []; //大类
                this.querys.zlid = []; //中类
                this.querys.xlid = []; //小类
                this.querys.xbid = []; //性别
                this.$message('已重置所有筛选条件了')
            },
            //表1 获取表1数据
            getTable1(pdValue) {
				// 如果选择了时间段则走新增
				if(this.selectTime && this.selectTime.length>0 && pdValue == 1) {

					// 开始时间
					this.data1 = this.selectTime[0]
					// 结束时间
					this.data2 = this.selectTime[1]
					this.pdSfZj = false;
					this.createTable()
					return;
				}
				// 如果不存在则走查询
				this.querys.ppid = this.querys.ppid = this.querys.ppid.map(item => item.substring(item.indexOf('_') + 1));
				this.querys.nfid = this.querys.nfid = this.querys.nfid.map(item => item.substring(item.indexOf('_') + 1));
				this.querys.jjid = this.querys.jjid = this.querys.jjid.map(item => item.substring(item.indexOf('_') + 1));
				this.querys.dlid = this.querys.dlid = this.querys.dlid.map(item => item.substring(item.indexOf('_') + 1));
				this.querys.zlid = this.querys.zlid = this.querys.zlid.map(item => item.substring(item.indexOf('_') + 1));
				this.querys.xlid = this.querys.xlid = this.querys.xlid.map(item => item.substring(item.indexOf('_') + 1));
				this.querys.xbid = this.querys.xbid = this.querys.xbid.map(item => item.substring(item.indexOf('_') + 1));
				this.querys.bdid = this.querys.bdid = this.querys.bdid.map(item => item.substring(item.indexOf('_') + 1));
                this.loading1 = true
                this.loadingGetTable = true;
                this.$http.post('/scm/bi/getPages/jxcbb', {
                        page: this.tablePage1.currentPage,
                        limit: this.tablePage1.pageSize,
                        ...this.querys
                    })
                    .then(res => {
                        this.loading1 = false;
                        this.loadingGetTable = false;
                        this.tableColumn1 = []; //初始化
                        if (res.data.code == 0) {
                            //
                            this.tableData1 = res.data.data;
                            this.tablePage1.totalResult = res.data.count;
                            if (res.data.count <= 0) {
                                this.$message('没有查询到数据');
                                return;
                            }

                            //
                            let obj = res.data.data[0]; //{name:“小白”,age:18,sex:“男”}
                            let newobj = Object.keys(obj)
                            // console.log(newobj);

                            var itemArr = [];
                            var itemObj = {};
                            var len = newobj.length;
                            for (let i = 0; i < len; i++) {
                                itemArr = [];
                                itemObj = {};
                                if (newobj[i] == 'rownum_' || newobj[i] == 'creatat' || newobj[i] == 'ppid' ||
                                    newobj[i] == 'cdid') {
                                    continue;
                                }
                                itemArr = newobj[i].split('_');
                                itemObj = {
                                    fieldcode: newobj[i],
                                    fieldname: itemArr[0],
                                    fieldseq: itemArr[1] || 1,
                                    showwidth: itemArr[2] || 87
                                };
                                this.tableColumn1.push(itemObj);
                            }
                            this.tableColumn1.sort(this.sortBy('fieldseq'));
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    })
                    .catch(e => {
                        this.loading1 = false;
                        this.loadingGetTable = false;
                        this.$message.error(e.message);
                    });
            },
            //根据传过来的字段进行排序
            sortBy(field) {
                return (x, y) => {
                    return x[field] - y[field]
                }
            },
            //表格分页组件
            handlePageChange1({
                currentPage,
                pageSize
            }) {
                this.tablePage1.currentPage = currentPage
                this.tablePage1.pageSize = pageSize
                this.getTable1();
            },
            //生成报表数据
            createTable() {
				if(this.pdSfZj){
					this.data1 = 'zhijie'
					this.data2 = 'zhijie'
				}
                this.$confirm('重新生成报表将会覆盖当前的查询结果.', '提示', {
                        type: 'warning'
                    })
                    .then(() => {
                        this.loading1 = true
                        this.loadingCreateTable = true
                        this.disabled = true;
                        this.$http.post('/scm/bi/createTable/jxcbb', {
							data1 : this.data1,
							data2 : this.data2
						})
                            .then(res => {
                                this.loading1 = false;
                                this.loadingCreateTable = false;
                                this.disabled = false;
                                if (res.data.code == 0) {
                                    this.$message.success(res.data.msg);
                                    this.getTable1(2);
                                    this.getTableTime();
                                } else {
                                    this.$message.error(res.data.msg);
                                }
                            })
                            .catch(e => {
                                this.loading1 = false;
                                this.loadingCreateTable = false;
                                this.disabled = false;
                                this.$message.error(e.message);
                            });
                    })
                    .catch(() => 0);
            },
            //生成EXCEL
            createExcel() {
                this.$confirm('重新生成EXCEL可能需要较长时间.', '提示', {
                        type: 'warning'
                    })
                    .then(() => {
                        this.loadingCreateExcel = true
                        this.disabled = true;

                        this.$http.post('/scm/bi/createExcel/jxcbb', {})
                            .then(res => {
                                this.loadingCreateExcel = false;
                                this.disabled = false;
                                this.getTableTime();
                                if (res.data.code == 0) {
                                    this.$message.success(res.data.msg);
                                } else {
                                    this.$message.error(res.data.msg);
                                }
                            })
                            .catch(e => {
                                this.loadingCreateExcel = false;
                                this.disabled = false;
                                this.$message.error(e.message);
                            });
                    })
                    .catch(() => 0);
            },
            //下载Excel
            async getExcel() {
                this.loadingGetExcel = true;
                this.disabled = true;
                await this.downloadFile('/scm/bi/getExcel/jxcbb', '进销存报表.xlsx', this.querys);
                this.loadingGetExcel = false;
                this.disabled = false;

                // 这种方式loading按钮不会生效 ！！！
                // await this.$confirm('确定下载查询的数据到EXCEL吗？数据量较多则可能需要较长时间.', '提示', {
                //         type: 'warning'
                //     })
                //     .then(() => {
                //         this.loadingGetExcel = true;
                //         this.disabled = true;
                //         this.downloadFile('/scm/bi/getExcel/jxcbb', '进销存报表.xlsx', this.querys);
                //         this.loadingGetExcel = false;
                //         this.disabled = false;
                //     })
                //     .catch(() => 0);

            },
            //下载所有Excel
            async downloadExcel() {
                this.loadingDownloadExcel = true;
                this.disabled = true;
                await this.downloadFile('/scm/bi/downloadExcel/jxcbb', '进销存报表.xlsx');
                this.loadingDownloadExcel = false;
                this.disabled = false;
            },
            //Vue通用下载方法 （async await设置为同步方法）
            async downloadFile(url, filename, params) {
                await this.axios
                    .request({
                        url: url,
                        method: 'post',
                        data: {
                            ...params
                        },
                        responseType: 'blob',
                        timeout: 3600000
                        //type: 'application/x-www-form-urlencoded'
                    })
                    .then(res => {
                        var blob = new Blob([res.data], {
                            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                        });
                        var downloadElement = document.createElement('a');
                        var href = window.URL.createObjectURL(blob); // 创建下载的链接
                        var contentFilename = (decodeURI(res.headers['content-disposition'])).split(
                            'filename=')[1]; //获取服务器传过来的文件名
                        downloadElement.href = href;
                        // downloadElement.download = decodeURI(res.headers['Content-Disposition'].split('filename=')[1]); // 下载后文件名
                        downloadElement.download = contentFilename || (filename || '下载的文件');
                        document.body.appendChild(downloadElement);
                        downloadElement.click(); // 点击下载
                        document.body.removeChild(downloadElement); // 下载完成移除元素
                        window.URL.revokeObjectURL(href); // 释放掉blob对象
                    });
            },

        }
    }
</script>

<style scoped>
    .container-div {
        height: calc(100vh - 110px);
        background-color: #ffffff;
        padding: 5px;
    }

    /* 屏幕尺寸大于767px则使用此样式  @media screen and (max-width: 768px) */
    @media screen and (min-width: 767px) {
        .container-div {
            height: calc(100vh - 110px);
        }
    }
	.oneRowCol {
		width: 150px;
		margin-right: 20px;
	}
	.selectTime .el-date-editor {
		width: 200px;
	}
	.ysy-label {
		float: left; text-align: right; width: 60px; font-size: 14px; font-weight: 800; color:#111111;
	}
</style>
